<template>
  <div class="app-container">
    <TheQueryForm :option="searchOption" @onSubmit="onSubmit" @onClear="onClear"></TheQueryForm>
    <el-row style="margin-bottom: 20px">
      <el-col :span="18">
        <el-radio-group
          size="small"
          v-model="queryParams.workerCategoryState"
          @change="onChangeTab"
        >
          <el-radio-button label>全部</el-radio-button>
          <el-radio-button label="YES">已开启接单</el-radio-button>
          <el-radio-button label="NO">已关闭订单</el-radio-button>
        </el-radio-group>
      </el-col>
      <el-col :span="6" style="display: flex; justify-content: flex-end">
        <el-button type="primary" size="small" @click="handleCreate">新建师傅</el-button>
        <el-button size="small" :loading="exportLoading" @click="handleExport">导出Excel</el-button>
      </el-col>
    </el-row>
    <TheTable
      ref="tableRefs"
      :tableOption="tableOption"
      :pageNo.sync="pageNo"
      :limit.sync="limit"
      :api="queryPageApi"
      :queryParams="queryParams"
    />
    <el-dialog
      title="师傅服务类目和报价"
      :visible.sync="dialogClassify"
      width="30%"
      modal-append-to-body
      center
    >
      <div class="content">
        <div
          class="item"
          v-for="(item, index) in classifyData"
          :key="'info_dialog_' + index"
          :style="'margin-bottom: 5px;'"
        >
          <el-tag
            size="small"
            style="margin-right:10px"
            :type="item.workerCategoryState === 'YES' ? 'success' : 'danger'"
          >{{ item.workerCategoryState | filterUserState }}</el-tag>
          <span class="name">{{ item.serviceCategoryFullName }}：</span>
          <span class="price">{{ item.price | filterPriceFormat }}</span>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="info" @click="dialogClassify = false">关 闭</el-button>
      </span>
    </el-dialog>
    <el-dialog title="服务区域" :visible.sync="dialogArea" width="30%" modal-append-to-body center>
      <div class="content">
        <div
          class="item"
          v-for="(item, index) in areaData"
          :key="'info_' + index"
          :style="index < 2 ? 'margin-bottom: 5px;' : ''"
        >
          <span
            class="state"
            style="padding-left: 27px"
            v-if="
              index > 0 && item.serviceLevel == areaData[index - 1].serviceLevel
            "
          ></span>
          <span class="state" v-else>{{ item.serviceLevel | filterAreaWeight }}：</span>
          <span class="name">{{ item.serviceAreaName }}</span>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="info" @click="dialogArea = false">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import ClassifyOfPrice from "./components/classifyOfPrice.vue";
import ServiceArea from "./components/serviceArea.vue";
import { filterPriceFormat } from "@/filters/index";
import { apiOperationWorkerPage, apiCommonDistrict } from "@/api/worker";
import { apiServiceCategoryTree } from "@/api/serviceCategory.js";

export default {
  components: { ClassifyOfPrice, ServiceArea },
  data() {
    const _this = this;
    return {
      dialogArea: false,
      areaData: [],
      dialogClassify: false,
      classifyData: [],

      queryPageApi: apiOperationWorkerPage,
      queryParams: {
        workerCategoryState: ""
      },
      pageNo: 1,
      limit: 10,
      exportLoading: false,
      searchOption: [
        {
          field: "workerId",
          label: "师傅ID",
          placeholder: "师傅ID",
          required: false,
          rules: [],
          type: "Input",
          defaultValue: ""
        },
        {
          field: "userPhoneNumber",
          label: "手机号",
          placeholder: "手机号",
          required: false,
          rules: [],
          type: "Input",
          defaultValue: ""
        },

        {
          type: "Select",
          field: "categoryId",
          label: "服务类目",
          placeholder: "服务类目",
          options: [],
          optionsValue: "categoryId",
          optionsKey: "categoryName",
          api: apiServiceCategoryTree,
          defaultValue: ""
        },
        {
          type: "Cascader",
          field: "serviceAreaId",
          label: "服务区域",
          placeholder: "服务区域",
          required: false,
          optionsKey: "name",
          optionsValue: "id",
          params: { pid: 0 },
          width: "400px",
          props: {
            checkStrictly: true,
            lazy: true,
            multiple: true,
            async lazyLoad(node, resolve) {
              let field = "";
              if (node.level > 0) {
                field = node.config.field;
              }
              const nodes = await _this.getDistrict(node.value || 0, field);
              resolve(nodes);
            }
          },
          defaultValue: ""
        },
        {
          type: "DatePickerRange",
          field: "time",
          label: "入驻时间",
          placeholder: "入驻时间"
        }
      ],
      tableOption: [
        {
          label: "师傅id",
          prop: "workerId",
          width: 100
        },
        {
          label: "师傅信息",
          prop: "info",
          width: 200,
          render(createElement, { row }) {
            const tags = row.internalLabel
              .map(item => (
                <div>
                  <el-tag size="small" style="margin:0 0 5px 5px">
                    {item}
                  </el-tag>
                </div>
              ))
              .splice(0, 3);
            const dom = (
              <div class="row">
                <div class="span4">
                  <el-avatar
                    style="width:80px;height:80px;"
                    src={row.avatar}
                  ></el-avatar>
                </div>
                <div class="span20">
                  <div>{row.workerName}</div>
                  <div>{row.userPhoneNumber}</div>
                  <div style="width:100%;">{tags.splice(0, 3)}</div>
                </div>
              </div>
            );
            return dom;
          }
        },
        {
          label: "服务类目和报价",
          prop: "category",
          width: 250,
          render(h, { row }) {
            try {
              const info = row.category;
              return h("el-row", [
                h(ClassifyOfPrice, {
                  domProps: {},
                  props: {
                    info: info
                  },
                  on: {
                    trigger() {
                      _this.classifyData = info;
                      _this.$nextTick(() => {
                        _this.dialogClassify = true;
                      });
                    }
                  }
                })
              ]);
            } catch (error) {
              return <div></div>;
            }
          }
        },
        {
          label: "服务区域",
          prop: "area",
          width: 340,
          render(h, { row }) {
            try {
              const info = [
                ...row.importTant,
                ...row.precedence,
                ...row.ordinary
                // { state: "1", name: "黑龙江省哈尔滨市呼兰区" },
              ];
              return h("el-row", [
                h(ServiceArea, {
                  domProps: {},
                  props: {
                    info: info
                  },
                  on: {
                    trigger() {
                      _this.areaData = info;
                      _this.$nextTick(() => {
                        console.log(_this.areaData);
                        _this.dialogArea = true;
                      });
                    }
                  }
                })
              ]);
            } catch (error) {
              return <div></div>;
            }
          }
        },
        {
          label: "累计完成订单",
          prop: "orderCount",
          width: 80,
          formatter({ orderCount }) {
            return orderCount || 0;
          }
        },
        {
          label: "30天完成订单",
          prop: "monthOrderCount",
          width: 80,
          formatter({ monthOrderCount }) {
            return monthOrderCount || 0;
          }
        },
        {
          label: "保证金",
          prop: "securityDeposit",
          width: 70,
          formatter({ securityDeposit }) {
            return securityDeposit ? filterPriceFormat(securityDeposit) : "0";
          }
        },
        {
          label: "入驻时间",
          width: 80,
          prop: "auditTime",
          render(createElement, { row }) {
            try {
              const strArr = row.auditTime.split(" ");
              const dom = (
                <div class="">
                  <div>{strArr[0]}</div>
                  <div>{strArr[1]}</div>
                </div>
              );
              return dom;
            } catch (error) {
              return <div></div>;
            }
          }
        },

        {
          label: "操作",
          width: 80,
          prop: "operate",
          fixed: "right",
          render(h, { row }) {
            return h("el-row", [
              h("el-link", {
                domProps: {
                  innerHTML: "查看详情"
                },
                props: {
                  type: "primary"
                },
                on: {
                  click() {
                    _this.$router.push({
                      path: "/worker/personDetail",
                      query: {
                        workerId: row.workerId,
                        workerFrom: "platform"
                      }
                    });
                  }
                }
              })
            ]);
          }
        }
      ]
    };
  },
  mounted() {},
  methods: {
    onView(row) {
      // this.$router.push({
      //   path: "/receipt/detail",
      //   query: { contractId: row.contractId }
      // });
    },
    // 新建师傅
    handleCreate() {
      this.$router.push({
        path: "/worker/createPerson",
        query: {}
      });
    },
    onChangeTab() {
      this.pageNo = 1;
    },
    // 导出
    async handleExport() {
      this.exportLoading = true;
      const res = await apiOperationWorkerPage({
        pageNo: 1,
        pageSize: -1,
        ...this.queryParams
      });
      if (res.code === "SUCCESS") {
        let header = [
          {
            title: "师傅id",
            prop: "workerId",
            valueType: "s"
          },
          {
            title: "师傅信息",
            prop: "",
            children: [
              { title: "姓名", prop: "workerName", valueType: "s" },
              { title: "手机号", prop: "userPhoneNumber", valueType: "s" }
            ]
          },
          {
            title: "服务类目和报价",
            prop: "promoterType",
            valueType: "s"
          },
          {
            title: "服务区域",
            prop: "",
            valueType: "s",
            children: [
              {
                title: "重",
                prop: "IMPORTANT_POINT",
                valueType: "s"
              },
              {
                title: "优",
                valueType: "s",
                prop: "PRECEDENCE"
              },
              {
                title: "普通",
                valueType: "s",
                prop: "COMMON"
              }
            ]
          },
          {
            title: "累计完成订单",
            prop: "orderCount",
            valueType: "s"
          },
          {
            title: "30天完成订单",
            prop: "monthOrderCount",
            valueType: "s"
          },
          { title: "保证金", prop: "securityDeposit", valueType: "s" },
          {
            title: "入驻时间",
            prop: "auditTime",
            valueType: "s"
          }
        ];

        let dataSource = res.data.map(item => {
          return {
            ...item,
            promoterType: item.category
              .map(row => {
                return `${this.$filters.filterUserState(
                  row.workerCategoryState
                )} ${
                  row.serviceCategoryFullName
                } ${this.$filters.filterPriceFormat(row.price)}`;
              })
              .join(";"),
            securityDeposit: filterPriceFormat(item.securityDeposit),
            IMPORTANT_POINT: item.importTant
              .map(row => row.serviceAreaName)
              .join(";"),
            PRECEDENCE: item.precedence
              .map(row => row.serviceAreaName)
              .join(";"),
            COMMON: item.ordinary.map(row => row.serviceAreaName).join(";")
          };
        });
        const option = {
          dataSource: dataSource,
          header: header,
          fileName: "师傅明细"
        };
        window.$Json2Excel(option);
        this.exportLoading = false;
      } else {
        this.$message({
          message: "导出操作失败,请重试",
          type: "warring"
        });
        this.exportLoading = false;
      }
    },

    onSubmit({ values }) {
      console.log(values);
      if (values.hasOwnProperty("time")) {
        values = {
          ...values,
          auditTimeBegin:
            values.time && values.time[0] ? values.time[0] + " 00:00:00" : "",
          auditTimeEnd:
            values.time && values.time[1] ? values.time[1] + " 23:59:59" : ""
        };
        delete values.time;
      }
      if (
        values.hasOwnProperty("serviceAreaId") &&
        values.serviceAreaId &&
        values.serviceAreaId.length > 0
      ) {
        values = {
          ...values,
          serviceAreaId: values.serviceAreaId.map(item => {
            console.log(item, "aaa");
            return item[item.length - 1];
          })
        };
      }
      this.queryParams = { ...this.queryParams, ...values };
    },
    onClear() {
      this.queryParams = {
        workerCategoryState: ""
      };
    },
    getDistrict(pid, field) {
      return new Promise((resolve, reject) => {
        apiCommonDistrict({ pid })
          .then(res => {
            resolve(
              res.data.map(item => {
                return {
                  value: item.id,
                  label: item.name,
                  type: item.level,
                  leaf:
                    field && field === "common"
                      ? item.level == "area"
                      : item.level == "street"
                };
              })
            );
          })
          .catch(err => {
            reject([]);
          });
      });
    }
  }
};
</script>
<style scoped lang="scss">
::v-deep .row {
  display: flex;
  align-items: center;
  .span4 {
    flex: 1;
    margin-right: 20px;
  }
  .span20 {
    flex: 5;
    text-align-last: left;
  }
}
</style>
